package com.vincent.videocompressor;

import android.content.Context;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Build;
import android.support.annotation.RequiresApi;


import java.io.File;
import java.io.IOException;

/**
 * Created by huangwei on 2018/3/8 0008.
 */

public class VideoUtil {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static int selectTrack(MediaExtractor extractor, boolean audio) {
        int numTracks = extractor.getTrackCount();
        for (int i = 0; i < numTracks; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (audio) {
                if (mime.startsWith("audio/")) {
                    return i;
                }
            } else {
                if (mime.startsWith("video/")) {
                    return i;
                }
            }
        }
        return -5;
    }



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static float getAveFrameRate(String videoPath) throws IOException {
        MediaExtractor extractor = new MediaExtractor();
        extractor.setDataSource(videoPath);
        int trackIndex = VideoUtil.selectTrack(extractor, false);
        extractor.selectTrack(trackIndex);
        long lastSampleTimeUs = 0;
        int frameCount = 0;
        while (true) {
            long sampleTime = extractor.getSampleTime();
            if (sampleTime < 0) {
                break;
            } else {
                lastSampleTimeUs = sampleTime;
            }
            frameCount++;
            extractor.advance();
        }
        extractor.release();
        return frameCount / (lastSampleTimeUs / 1000f / 1000f);
    }


    public static File getVideoCacheDir(Context context) {
        File cacheDir = new File(context.getCacheDir(), "video/");
        cacheDir.mkdirs();
        return cacheDir;
    }
}
